<template>
  <div class="classification-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h2>视频分类设置</h2>
        </div>
      </template>

      <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="视频目录" prop="directory">
          <FileSelector v-model="formData.directory" placeholder="请输入视频目录路径" storage-key="recentDirectories" />
        </el-form-item>

        <el-form-item label="扫描间隔(分钟)" prop="sleepTime">
          <el-input-number v-model="formData.sleepTime" :min="1" :max="1440" />
        </el-form-item>

        <el-form-item label="目标语言" prop="language">
          <el-select v-model="formData.language">
            <el-option label="越南语" value="VN" />
            <el-option label="泰语" value="TH" />
            <el-option label="英语" value="EN" />
            <el-option label="印尼语" value="ID" />
            <el-option label="马来语" value="MS" />
            <el-option label="ASCII" value="ASCII" />
          </el-select>
        </el-form-item>

        <el-form-item label="功能选择">
          <el-switch v-model="formData.enableClassification" active-text="启用分类功能" inactive-text="禁用分类功能"
            style="margin-right: 20px" />
          <el-switch v-model="formData.enableTranslation" active-text="启用翻译功能" inactive-text="禁用翻译功能" />
        </el-form-item>

        <el-form-item label="广告检测">
          <el-switch v-model="formData.adDetection" active-text="启用 (有广告的视频会被标记为不可播放)" />
        </el-form-item>

        <el-form-item label="水印检测">
          <el-switch v-model="formData.watermarkDetection" active-text="启用 (移动水印视频会被标记为不可播放，固定水印会单独分类)" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="startClassification" :loading="processing" :disabled="processing">
            开始运行 </el-button>
          <el-button type="danger" @click="stopClassification" :disabled="!processing">
            停止运行
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <log-console :logs="logs" @clear-logs="clearLogs" class="log-section" />
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import LogConsole from '@/components/LogConsole.vue';
import classificationService from '@/services/classificationService.js';
import FileSelector from '@/components/FileSelector.vue';
import settingsService from '@/services/settingsService.js';

export default {
  name: 'ClassificationView',
  components: {
    LogConsole,
    FileSelector,
  },
  setup() {
    const formRef = ref(null);
    const processing = ref(false);
    const continuousMode = ref(true);
    const logs = ref([]);
    const statusInterval = ref(null);
    const continueTimer = ref(null);
    const showResults = ref(false);

    const saveSettings = () => {
      settingsService.saveSettings('classification_settings', {
        directory: formData.directory,
        sleepTime: formData.sleepTime,
        language: formData.language,
        enableClassification: formData.enableClassification,
        enableTranslation: formData.enableTranslation,
        adDetection: formData.adDetection,
        watermarkDetection: formData.watermarkDetection,
        continuousMode: continuousMode.value
      });
    };
    const formData = reactive({
      directory: '',
      sleepTime: 60,
      language: 'VN',
      enableClassification: true,
      enableTranslation: true,
      adDetection: true,
      watermarkDetection: true,
    });

    const rules = {
      directory: [
        { required: true, message: '请选择视频目录', trigger: 'blur' }
      ],
      sleepTime: [
        { required: true, message: '请输入扫描间隔', trigger: 'blur' },
        { type: 'number', min: 1, message: '扫描间隔必须大于0', trigger: 'blur' }
      ]
    };

    // 启动状态轮询
    const startStatusPolling = () => {
      stopStatusPolling(); // 确保先停止现有的轮询

      statusInterval.value = setInterval(async () => {
        try {
          const response = await classificationService.getStatus();
          if (response.logs && response.logs.length > 0) {
            logs.value = response.logs;
          }

          if (response.status === 'completed' && processing.value) {
            processing.value = false;
            stopStatusPolling();
            ElMessage.success('分类任务已完成');
          }
        } catch (error) {
          console.error('获取状态失败:', error);
        }
      }, 2000);
    };

    // 停止状态轮询
    const stopStatusPolling = () => {
      if (statusInterval.value) {
        clearInterval(statusInterval.value);
        statusInterval.value = null;
      }
    };

    // 选择目录
    const selectDirectory = async () => {
      try {
        // 这里应该调用Electron的API或通过后端API选择目录
        // 在纯网页环境下无法直接访问文件系统，可以考虑让用户手动输入
        ElMessage.info('在网页环境中，请直接输入目录路径');
      } catch (error) {
        ElMessage.error('选择目录失败: ' + error.message);
      }
    };

    // 开始分类
    const startClassification = async () => {
      if (!formRef.value) return;

      try {
        await formRef.value.validate();
        // 验证 API Key
        const apiKey = settingsService.getGlobal("apiKey");
        if (!apiKey) {
          ElMessage.warning('请前往系统设置页面， 配置OpenAI API Key');
          return;
        }
        processing.value = true;

        const settings = {
          api_key: apiKey,
          enable_classification: formData.enableClassification,
          enable_translation: formData.enableTranslation,
          ad_detection: formData.adDetection,
          watermark_detection: formData.watermarkDetection,
          language: formData.language,
          sleep_time: formData.sleepTime
        };

        const response = await classificationService.processDirectory(
          formData.directory,
          settings
        );

        if (response.success) {
          ElMessage.success('开始处理目录');
          startStatusPolling();

          saveSettings(); // 保存设置
          showResults.value = true;

          // 持续运行模式设置
          if (continuousMode.value) {
            const sleepTimeMs = formData.sleepTime * 60 * 1000;
            if (continueTimer.value) {
              clearTimeout(continueTimer.value);
            }

            continueTimer.value = setTimeout(() => {
              if (!processing.value) { // 只有上一个任务完成才启动新任务
                startClassification(); // 递归调用自身，实现持续运行
              }
            }, sleepTimeMs);
          }
        } else {
          processing.value = false;
          ElMessage.error(response.message || '启动失败');
        }
      } catch (error) {
        processing.value = false;
        if (error.errors) {
          ElMessage.error('请检查表单输入');
        } else {
          ElMessage.error('启动失败: ' + error.message);
        }
      }
    };

    // 停止分类
    const stopClassification = async () => {
      try {
        // 清除持续运行的计时器
        if (continueTimer.value) {
          clearTimeout(continueTimer.value);
          continueTimer.value = null;
        }

        const response = await classificationService.stopProcessing();
        if (response.success) {
          ElMessage.success('已停止分类任务');
          processing.value = false;
          stopStatusPolling();
        } else {
          ElMessage.error(response.message || '停止失败');
        }
      } catch (error) {
        ElMessage.error('停止失败: ' + error.message);
      }
    };

    // 清空日志
    const clearLogs = () => {
      logs.value = [];
    };

    // 组件挂载和卸载
    onMounted(() => {
      // 加载保存的设置
      const savedSettings = settingsService.loadSettings('classification_settings');
      if (savedSettings) {
        formData.directory = savedSettings.directory || '';
        formData.sleepTime = savedSettings.sleepTime || 60;
        formData.language = savedSettings.language || 'VN';
        formData.enableClassification = savedSettings.enableClassification !== undefined ?
          savedSettings.enableClassification : true;
        formData.enableTranslation = savedSettings.enableTranslation !== undefined ?
          savedSettings.enableTranslation : true;
        formData.adDetection = savedSettings.adDetection !== undefined ?
          savedSettings.adDetection : true;
        formData.watermarkDetection = savedSettings.watermarkDetection !== undefined ?
          savedSettings.watermarkDetection : true;
        continuousMode.value = savedSettings.continuousMode !== undefined ?
          savedSettings.continuousMode : true;
      }
    });
    onUnmounted(() => {
      stopStatusPolling();
      if (continueTimer.value) {
        clearTimeout(continueTimer.value);
      }
    });

    return {
      formRef,
      formData,
      rules,
      logs,
      processing,
      continuousMode,
      selectDirectory,
      startClassification,
      stopClassification,
      clearLogs,
      saveSettings,
      showResults,
    };
  }
};
</script>

<style scoped>
.classification-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.log-section {
  margin-top: 20px;
}

.result-section {
  margin-top: 20px;
}


:deep(.el-card__header) {
  padding: 0 1em;
}

:deep(.el-card__header h2) {
  line-height: 1em;
  font-size: 16px;
}
</style>